const totalConfig = require('../config/templateConfig').totalConfig;
let skillConfig = totalConfig.skill;

class BattleHandle {
    constructor() {}
    attack(p1Component, p2Component) {
        let p1 = p1Component.fightAttri;
        let p2 = p2Component.fightAttri;
        let p1Skills = p1.skills;
        let p1SkillsCd = p1.skillsCd;
        let p1SkillsCdCopy = p1SkillsCd.slice();
        let p2Skills = p2.skills;
        let p2SkillsCd = p2.skillsCd;
        let p2SkillsCdCopy = p2SkillsCd.slice();
        while (true) {
            for (let [index, item] of p1SkillsCdCopy.entries()) {
                let cd = p1SkillsCdCopy[index] -= 200;
                if (cd === 0) {
                    let skillId = p1Skills[index];
                    let item = skillConfig[skillId];
                    if (p2.hp > 0) {
                        let damage = this.calcDemage(p1, p2, item)
                        p2.hp -= damage;
                        if (p2.hp <= 0) {
                            return 1;
                        }
                    }
                } else if (cd < 0) {
                    p1SkillsCdCopy[index] = p1SkillsCd[index];
                }
            }

            for (let [index, item] of p2SkillsCdCopy.entries()) {
                p2SkillsCdCopy[index] -= 200;
                let cd = p2SkillsCdCopy[index];
                if (cd === 0) {
                    let skillId = p2Skills[index];
                    let item = skillConfig[skillId];
                    if (p1.hp > 0) {
                        let damage = this.calcDemage(p2, p1, item);
                        p1.hp -= damage;
                        if (p1.hp <= 0) {
                            return 0;
                        }
                    }
                } else if (cd < 0) {
                    p2SkillsCdCopy[index] = p2SkillsCd[index];
                }
            }
        }
    }
    calcDemage(attacker, defender, skill) {
        let hurt = attacker.attack + skill.attack;
        let damage = parseInt((hurt * hurt) / (defender.defend + hurt));
        return damage;
    }
}



let battleHandle = new BattleHandle();
module.exports = battleHandle;